//
//  BSKUserInfoViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/11.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import <LeanCloudSocial/AVOSCloudSNS.h>
#import <AVOSCloud/AVOSCloud.h>
#import <LeanCloudSocial/AVUser+SNS.h>
#import <UIImageView+WebCache.h>
#import <KVNProgress/KVNProgress.h>
#import "BSKUserInfoViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKTheme.h"
#import "BSKconsts.h"
#import "IQKeyboardManager.h"
#import "UIViewController+BSKToast.h"
#import "BSKStringCheck.h"

@interface BSKUserInfoViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource>
@property (strong, nonatomic) UIView *navView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UILabel *titleLabel;

@property (strong, nonatomic) UIScrollView *contentScrollView;
@property (strong, nonatomic) UIImageView *headImageView;
@property (strong, nonatomic) UITextField *nickNameTextField;
@property (strong, nonatomic) UILabel *nickNameLabel;
@property (strong, nonatomic) UIView *sexView;
@property (strong, nonatomic) UITextField *sexTextField;
@property (strong, nonatomic) UILabel *sexLabel;
@property (strong, nonatomic) UITextField *birthdayTextField;
@property (strong, nonatomic) UILabel *birthdayLabel;
@property (strong, nonatomic) UIButton *saveButton;
@property (assign, nonatomic) NSInteger flag;
@property (strong, nonatomic) UIDatePicker *datePicker;
@property (strong, nonatomic) UIPickerView *picker;
@property (strong, nonatomic) NSArray *sexArr;

@end

@implementation BSKUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.9525 green:0.9525 blue:0.9525 alpha:1.0];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [self initializeUserInterface];
    [self initializeUIStatus];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShowAction) name:UIKeyboardDidShowNotification object:nil];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _flag = 0;
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (_flag == 0) {
        CGFloat contentHeight = 45 + 80 + 40 + 40 + 40 + 40 + 40 + 40 + 40;
        if (self.contentScrollView.height_sd <= contentHeight) {
            self.contentScrollView.contentSize = CGSizeMake(self.view.width, contentHeight);
        } else {
            self.contentScrollView.contentSize = self.contentScrollView.size_sd;
        }
        _flag = 1;
    }
}
- (void)initializeUserInterface {
    self.sexArr = @[@"--", @"男", @"女"];
    
    UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *coverView = [[UIVisualEffectView alloc]initWithEffect:efect];
    UIImageView *imageView = [[UIImageView alloc] init];
    self.navView = [[UIView alloc] init];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.titleLabel = [[UILabel alloc] init];
    self.contentScrollView = [[UIScrollView alloc] init];
    self.headImageView = [[UIImageView alloc] init];
    self.nickNameTextField = [[UITextField alloc] init];
    self.nickNameLabel = [[UILabel alloc] init];
    self.sexView = [[UIView alloc] init];
    self.sexTextField = [[UITextField alloc] init];
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sexLabel = [[UILabel alloc] init];
    self.birthdayTextField = [[UITextField alloc] init];
    UIButton *coverButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.birthdayLabel = [[UILabel alloc] init];
    self.saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.datePicker = [[UIDatePicker alloc] init];
    self.picker = [[UIPickerView alloc] init];
    
    [self.view addSubview:imageView];
    [self.view addSubview:coverView];
    [self.view addSubview:self.navView];
    [self.navView addSubview:self.backButton];
    [self.navView addSubview:self.titleLabel];
    [self.view addSubview:self.contentScrollView];
    [self.contentScrollView addSubview:self.headImageView];
    [self.contentScrollView addSubview:self.nickNameTextField];
    [self.contentScrollView addSubview:self.nickNameLabel];
    [self.contentScrollView addSubview:self.sexView];
    [self.contentScrollView addSubview:self.sexTextField];
    [self.contentScrollView addSubview:coverBtn];
    [self.contentScrollView addSubview:self.sexLabel];
    [self.contentScrollView addSubview:self.birthdayTextField];
    [self.contentScrollView addSubview:coverButton];
    [self.contentScrollView addSubview:self.birthdayLabel];
    [self.view addSubview:self.saveButton];
    
    coverView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    
    imageView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    imageView.image = [BSKTheme curentTheme].themeImage;
    
    self.navView.sd_layout.topEqualToView(self.view)
    .widthRatioToView(self.view, 1)
    .heightIs(StatusBarHeight + NavigationBarHeight);
    self.navView.backgroundColor = [BSKTheme curentTheme].themeColor;
    
    self.backButton.sd_layout.topSpaceToView(self.navView, StatusBarHeight + 5)
    .leftSpaceToView(self.navView, 5)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    [self.backButton setImage:[UIImage imageNamed:@"back" ] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.titleLabel.sd_layout.centerXIs(self.view.centerX)
    .centerYEqualToView(self.backButton);
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = @"个人信息";
    [self.titleLabel sizeToFit];
    
    self.contentScrollView.sd_layout.topSpaceToView(self.navView, 0)
    .widthRatioToView(self.view, 1)
    .leftEqualToView(self.view)
    .bottomSpaceToView(self.view, 80);
    self.contentScrollView.bounces = NO;
    self.contentScrollView.showsVerticalScrollIndicator = NO;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headImageAction)];
    self.headImageView.sd_layout.topSpaceToView(self.contentScrollView, 45)
    .centerXIs(self.view.centerX)
    .heightIs(80)
    .widthIs(80);
    [self.headImageView addGestureRecognizer:tapGesture];
    self.headImageView.userInteractionEnabled = YES;
    self.headImageView.layer.cornerRadius = self.headImageView.width / 2;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.image = [UIImage imageNamed:@"login-no"];
    
    self.nickNameTextField.sd_layout.topSpaceToView(self.headImageView, 40)
    .centerXIs(self.view.centerX)
    .widthIs(self.view.width / 2.5)
    .heightIs(40);
    self.nickNameTextField.text = @"MicroMemory";
    self.nickNameTextField.placeholder = @"请输入用户昵称";
    [self.nickNameTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.nickNameTextField.textColor = [UIColor whiteColor];
    self.nickNameTextField.textAlignment = NSTextAlignmentCenter;
    self.nickNameTextField.layer.cornerRadius = 10;
    self.nickNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.nickNameTextField.layer.borderWidth = 1;
    self.nickNameTextField.layer.borderColor = [UIColor whiteColor].CGColor;
    self.nickNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.nickNameLabel.sd_layout.centerYEqualToView(self.nickNameTextField)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.nickNameTextField, 30)
    .heightIs(30);
    self.nickNameLabel.text = @"昵称";
    self.nickNameLabel.textColor = [UIColor whiteColor];
    self.nickNameLabel.textAlignment = NSTextAlignmentRight;
    
    self.sexView.sd_layout.topSpaceToView(self.nickNameTextField, 40)
    .centerXIs(self.view.centerX)
    .widthIs(self.view.width / 2.5)
    .heightIs(40);
    
    self.picker.delegate = self;
    self.picker.dataSource = self;
    
    self.sexTextField.sd_layout.topSpaceToView(self.nickNameTextField, 40)
    .centerXIs(self.view.centerX)
    .widthIs(self.view.width / 2.5)
    .heightIs(40);
    self.sexTextField.text = @"--";
    self.sexTextField.placeholder = @"请选择性别";
    self.sexTextField.textColor = [UIColor whiteColor];
    self.sexTextField.textAlignment = NSTextAlignmentCenter;
    self.sexTextField.layer.cornerRadius = 10;
    self.sexTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.sexTextField.layer.borderWidth = 1;
    self.sexTextField.layer.borderColor = [UIColor whiteColor].CGColor;
    self.sexTextField.inputView = self.picker;
    [[self.sexTextField valueForKey:@"textInputTraits"] setValue:[UIColor clearColor] forKey:@"insertionPointColor"];
    
    coverBtn.sd_layout.topEqualToView(self.sexTextField)
    .leftEqualToView(self.sexTextField)
    .rightEqualToView(self.sexTextField)
    .bottomEqualToView(self.sexTextField);
    coverBtn.backgroundColor = [UIColor clearColor];
    coverBtn . tag = 10001;
    [coverBtn addTarget:self action:@selector(coverButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.sexLabel.sd_layout.centerYEqualToView(self.sexTextField)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.sexTextField, 30)
    .heightIs(30);
    self.sexLabel.text = @"性别";
    self.sexLabel.textColor = [UIColor whiteColor];
    self.sexLabel.textAlignment = NSTextAlignmentRight;
    
    [self.datePicker setDatePickerMode:UIDatePickerModeDate];
    [self.datePicker addTarget:self action:@selector(datePickerValueChange:) forControlEvents:UIControlEventValueChanged];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
    self.datePicker.minimumDate = [formatter dateFromString:@"1900-01-01"];
    self.datePicker.maximumDate =  [NSDate dateWithTimeInterval:-24 * 60 * 60 sinceDate:localeDate];
    self.datePicker.date = self.datePicker.maximumDate;
    
    
    self.birthdayTextField.sd_layout.topSpaceToView(self.sexView, 40)
    .centerXIs(self.view.centerX)
    .widthIs(self.view.width / 2.5)
    .heightIs(40);
    self.birthdayTextField.text = [formatter stringFromDate:self.datePicker.date];
    self.birthdayTextField.placeholder = @"请设置生日";
    self.birthdayTextField.textColor = [UIColor whiteColor];
    self.birthdayTextField.textAlignment = NSTextAlignmentCenter;
    self.birthdayTextField.layer.cornerRadius = 10;
    self.birthdayTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.birthdayTextField.layer.borderWidth = 1;
    self.birthdayTextField.layer.borderColor = [UIColor whiteColor].CGColor;
    self.birthdayTextField.inputView = self.datePicker;
    [[self.birthdayTextField valueForKey:@"textInputTraits"] setValue:[UIColor clearColor] forKey:@"insertionPointColor"];
    
    coverButton.sd_layout.topEqualToView(self.birthdayTextField)
    .leftEqualToView(self.birthdayTextField)
    .rightEqualToView(self.birthdayTextField)
    .bottomEqualToView(self.birthdayTextField);
    coverButton.backgroundColor = [UIColor clearColor];
    [coverButton addTarget:self action:@selector(coverButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.birthdayLabel.sd_layout.centerYEqualToView(self.birthdayTextField)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.birthdayTextField, 30)
    .heightIs(30);
    self.birthdayLabel.text = @"生日";
    self.birthdayLabel.textColor = [UIColor whiteColor];
    self.birthdayLabel.textAlignment = NSTextAlignmentRight;
    
    self.saveButton.sd_layout.bottomSpaceToView(self.view, 15)
    .leftSpaceToView(self.view, 30)
    .rightSpaceToView(self.view, 30)
    .heightIs(50);
    self.saveButton.backgroundColor = [BSKTheme curentTheme].themeColor;
    self.saveButton.layer.cornerRadius = 10;
    self.saveButton.layer.masksToBounds = YES;
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.saveButton addTarget:self action:@selector(saveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.nickNameTextField.backgroundColor = [UIColor clearColor];
    self.sexTextField.backgroundColor = [UIColor clearColor];
    self.birthdayTextField.backgroundColor = [UIColor clearColor];
}
- (void)initializeUIStatus {
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser[@"nickName"]) {
        self.nickNameTextField.text = currentUser[@"nickName"];
    }
    if (currentUser[@"userHeader"]) {
        NSURL * url = [NSURL URLWithString:[currentUser objectForKey:@"userHeader"]];
        [self.headImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"login-no"]];
    }
    if (currentUser[@"birthday"]) {
        self.birthdayTextField.text = currentUser[@"birthday"];
    }
    if (currentUser[@"sex"]) {
        self.sexTextField.text = currentUser[@"sex"];
    }
}
#pragma mark - 自定义方法
- (void)headImageAction {
    UIAlertController *alertControler = [UIAlertController alertControllerWithTitle:@"上传头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //防止循环引用
    __weak typeof(self) weakSelf = self;
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf selectAlbum];
    }];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf takePhoto];
    }];
    
    [alertControler addAction:cancelAction];
    [alertControler addAction:albumAction];
    [alertControler addAction:takePhotoAction];
    [self presentViewController:alertControler animated:YES completion:nil];
    
}
//相册选择照片
- (void)selectAlbum {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    //资源类型
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //是否允许编辑
    imagePicker.allowsEditing = YES;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}
//拍照
- (void)takePhoto {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误！无法连接到相机" message:@"请检查您的相关设置或者摄像头" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
        
        return;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    //资源类型
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //是否允许编辑
    imagePicker.allowsEditing = YES;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
    
    
}
- (void)coverButtonAction:(UIButton *)sender {
    if (sender.tag == 10001) {
        [self.sexTextField becomeFirstResponder];
    } else {
        [self.birthdayTextField becomeFirstResponder];
    }
}
- (void)keyboardShowAction {
    if ([self.birthdayTextField isFirstResponder]) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        if ([formatter dateFromString:self.birthdayTextField.text]) {
            [self.datePicker setDate:[formatter dateFromString:self.birthdayTextField.text] animated:YES];
        }
    } else if ([self.sexTextField isFirstResponder]) {
        NSInteger row = 0;
        if ([self.sexTextField.text isEqualToString:@"--"]) {
            row = 0;
        } else if ([self.sexTextField.text isEqualToString:@"男"]) {
            row = 1;
        } else {
            row = 2;
        }
        [self.picker selectRow:row inComponent:0 animated:YES];
    }
}
- (void)datePickerValueChange:(UIDatePicker *)sender {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    self.birthdayTextField.text = [formatter stringFromDate:sender.date];
}
- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)saveButtonAction:(UIButton *)sender {
    sender.enabled = NO;
    __weak typeof(self) weakSelf = self;
    if (![self textFieldCheck:self.nickNameTextField]) {
        sender.enabled = YES;
    } else {
        [KVNProgress show];
        [[AVUser currentUser] setObject:self.nickNameTextField.text forKey:@"nickName"];
        [[AVUser currentUser] setObject:self.birthdayTextField.text forKey:@"birthday"];
        [[AVUser currentUser] setObject:self.sexTextField.text forKey:@"sex"];
        [[AVUser currentUser] saveEventually:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                AVQuery *query = [AVQuery queryWithClassName:@"_File"];
                [query whereKey:@"name" containsString:[NSString stringWithFormat:@"%@Header.png", [AVUser currentUser].objectId]];
                [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    NSArray<AVFile *> *headerImages = objects;
                    for (AVFile *file in headerImages) {
                        [file deleteInBackground];
                    }
                }];
                NSData *data = UIImagePNGRepresentation(self.headImageView.image);
                AVFile *file = [AVFile fileWithName:[NSString stringWithFormat:@"%@Header.png", [AVUser currentUser].objectId] data:data];
                [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        NSString *fileUrl = file.url;
                        [[AVUser currentUser] setObject:fileUrl forKey:@"userHeader"];
                        [[AVUser currentUser] saveEventually];
                        [[NSNotificationCenter defaultCenter]postNotificationName:BSKuserStatusChangeNotification object:self.headImageView.image];
                        [KVNProgress dismiss];
                        [weakSelf.navigationController MakeToast:@"修改成功！" WithTime:1.5];
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                    } else {
                        [KVNProgress dismiss];
                        [weakSelf MakeToast:@"保存失败，请检查网络后重试" WithTime:1.5];
                        sender.enabled = YES;
                    }
                }];
                
            } else {
                [KVNProgress dismiss];
                [weakSelf MakeToast:@"保存失败，请检查网络后重试" WithTime:1.5];
                sender.enabled = YES;
            }
        }];
    }
}
- (BOOL)textFieldCheck:(UITextField *)textField {
    if (textField == self.nickNameTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"请输入昵称！" WithTime:1.5];
            return NO;
        }  else if (![BSKStringCheck validateNickname:textField.text]) {
            [self MakeToast:@"昵称过长" WithTime:1.5];
            return NO;
        }
    }
    return YES;
}
#pragma mark - UIPickerviewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.sexArr count];
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return self.sexArr[row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.sexTextField.text = self.sexArr[row];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    self.headImageView.image = info[@"UIImagePickerControllerEditedImage"];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
